'use client'

import { createContext, useContext, ReactNode } from 'react'
import { ProjectType } from '@/components/modals/NewProjectModal'
import { Attachment } from '@/components/modals/AttachmentPreviewModal'

// 定义模态框上下文类型
interface ModalsContextType {
  // 新建项目模态框
  openNewProject: (params: {
    onCreateProject: (title: string, description: string, type: ProjectType) => void;
  }) => void;
  
  // 新建章节模态框
  openNewChapter: (params: {
    projectId: string;
    onCreateChapter: (projectId: string, title: string, order: number) => void;
    lastChapterNumber?: number;
  }) => void;
  
  // 设置模态框
  openSettings: (params: {
    initialSettings?: any;
    onSaveSettings: (settings: any) => void;
  }) => void;
  
  // 确认对话框
  openConfirmation: (params: {
    title: string;
    message: string;
    onConfirm: () => void;
    confirmText?: string;
    cancelText?: string;
    isDangerous?: boolean;
  }) => void;
  
  // 附件预览模态框
  openAttachmentPreview: (params: {
    attachment: Attachment;
    onEdit?: (attachment: Attachment) => void;
  }) => void;
}

// 创建模态框上下文
export const ModalsContext = createContext<ModalsContextType | undefined>(undefined)

// 模态框上下文提供者组件
export const ModalsProvider = ({ children }: { children: ReactNode }) => {
  // 定义打开模态框的函数
  const openNewProject = (params: Parameters<ModalsContextType['openNewProject']>[0]) => {
    // 将通过ModalManager组件实现
    window.dispatchEvent(new CustomEvent('open-new-project-modal', { detail: params }))
  }
  
  const openNewChapter = (params: Parameters<ModalsContextType['openNewChapter']>[0]) => {
    window.dispatchEvent(new CustomEvent('open-new-chapter-modal', { detail: params }))
  }
  
  const openSettings = (params: Parameters<ModalsContextType['openSettings']>[0]) => {
    window.dispatchEvent(new CustomEvent('open-settings-modal', { detail: params }))
  }
  
  const openConfirmation = (params: Parameters<ModalsContextType['openConfirmation']>[0]) => {
    window.dispatchEvent(new CustomEvent('open-confirmation-modal', { detail: params }))
  }
  
  const openAttachmentPreview = (params: Parameters<ModalsContextType['openAttachmentPreview']>[0]) => {
    window.dispatchEvent(new CustomEvent('open-attachment-preview-modal', { detail: params }))
  }
  
  // 创建上下文值
  const contextValue: ModalsContextType = {
    openNewProject,
    openNewChapter,
    openSettings,
    openConfirmation,
    openAttachmentPreview
  }
  
  return (
    <ModalsContext.Provider value={contextValue}>
      {children}
    </ModalsContext.Provider>
  )
}

// 自定义钩子
export const useModals = (): ModalsContextType => {
  const context = useContext(ModalsContext)
  if (context === undefined) {
    throw new Error('useModals must be used within a ModalsProvider')
  }
  return context
}
